package org.zyj.io.pipeline.outbound1;

import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.StandardCharsets;

/**
 * 演示pipeline中的handler执行顺序
 * --
 * 全部都是OutboundHandler配置在Inbound后面
 * OutboundHandler不会被执行
 */
public class OutboundInitializer extends ChannelInitializer<NioSocketChannel> {

    @Override
    protected void initChannel(NioSocketChannel ch) throws Exception {
        ch.pipeline() //配置pipeline
                .addLast(new InboundHandler1())
                .addLast(new InboundHandler2())
                .addLast(new InboundHandler3())
                .addLast(new OutboundHandler1())
                .addLast(new OutboundHandler2())
        ;
    }

    static class InboundHandler1 extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("InboundHandler1; receive = " + msg.toString());
            ctx.fireChannelRead(1);
        }
    }

    static class InboundHandler2 extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("InboundHandler2; receive = " + msg.toString());
            ctx.fireChannelRead(2);
        }
    }

    static class InboundHandler3 extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("InboundHandler3; receive = " + msg.toString());
            ctx.writeAndFlush(3);
        }
    }


    static class OutboundHandler1 extends ChannelOutboundHandlerAdapter {
        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            System.out.println("OutboundHandler1; msg = " + msg.toString());
            ctx.write(Unpooled.copiedBuffer("OutboundHandler1", StandardCharsets.UTF_8));
        }
    }


    static class OutboundHandler2 extends ChannelOutboundHandlerAdapter {
        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            System.out.println("OutboundHandler2; msg = " + msg.toString());
            ctx.write(Unpooled.copiedBuffer("OutboundHandler2", StandardCharsets.UTF_8));
        }
    }


}
